﻿using System;
using System.Collections.Generic;
using ZSoftInstagram.DataAccess.Abstractions;
using ZSoftInstagram.Domain;
using ZSoftInstagram.Services.Abstraction;
using ZSoftInstagram.UI.ViewModels;
using System.Linq;
using System.Data.Entity;
using System.Threading.Tasks;
using ZSoftInstagram.Domain.User;

namespace ZSoftInstagram.Services
{
    public class CategoryService : ICategoryService
    {
        private IRepository<Category> _repository;

        public CategoryService(IRepository<Category> repository)
        {
            this._repository = repository;
        }

        public IRepository<Category> Repository
        {
            get
            {
                return this._repository;
            }
        }

        public Task<int> AddCategoryToFollowingsAsync(AddUserCategoryViewModel model, int userId)
        {
                this.Repository
                    .GetTypeRepository<ApplicationUser>()
                        .First(u => u.Id == userId && !u.FollowingCategories.Any(c => c.Id == model.Id), "FollowingCategories")
                        .FollowingCategories.Add(this._repository.First(c => c.Id == model.Id));
                            
            return this.Repository.SaveChangesAsync();
        }

        public Task<int> RemoveCategoryFromFollowingsUserAsync(AddUserCategoryViewModel model, int userId)
        {
            var user = this.Repository
                            .GetTypeRepository<ApplicationUser>()
                                .First(u => u.Id == userId, "FollowingCategories");
            user.FollowingCategories.Remove(user.FollowingCategories.First(c => c.Id == model.Id));
            return this.Repository.SaveChangesAsync();
        }

        public Task<List<CategoryViewModel>> GetAllCategoriesAsync()
        {
            return this._repository
                            .All()
                                .Select(c => new CategoryViewModel()
                                {
                                    Title = c.Title,
                                    Id = c.Id
                                }).ToListAsync();
        }

        public Task<List<CategoryViewModel>> GetUserFollowingCategories(int userId)
        {
            return this.Repository
                .Where(c => c.FollowingUsers.Any(u => u.Id == userId)).Select(c => new CategoryViewModel()
                {
                    Id = c.Id,
                    Title = c.Title
                }).ToListAsync();
        }
    }
}
